import { app, shell, BrowserWindow, ipcMain, screen } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { contextIsolated } from 'process'

function createWindow(): void {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 500,
    show: false,
    autoHideMenuBar: true,
    titleBarStyle: 'hidden',

    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

//子窗口的对象
let lyricsContext: any = {
  allowQuitting: false,
  isShow: true,
  lyricsWindow: null
}

let workWidth
let workHeight
function createLyricsWindow(): void {
  console.log('创建')
  lyricsContext.lyricsWindow = new BrowserWindow({
    width: 1000,
    height: 60,
    x: (workWidth - 1000) / 2,
    y: workHeight,
    show: false,
    autoHideMenuBar: true,
    transparent: true, //透明窗口
    frame: false, //无边框窗口
    resizable: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  lyricsContext.lyricsWindow.on('ready-to-show', () => {
    lyricsContext.lyricsWindow.show()
  })
  lyricsContext.lyricsWindow.webContents.openDevTools()

  // 开发环境：加载特定路由
  lyricsContext.lyricsWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#/about')
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  const primaryDisplay = screen.getPrimaryDisplay()
  workWidth = primaryDisplay.workAreaSize.width
  workHeight = primaryDisplay.workAreaSize.height

  ipcMain.handle('lyricsWindow', (event, payload) => {
    const window = lyricsContext.lyricsWindow
    const show = lyricsContext.isShow
    if (!window) {
      createLyricsWindow()
    }
    if (window && show) {
      lyricsContext.lyricsWindow.hide()
      lyricsContext.isShow = false
    } else if (window && !show) {
      lyricsContext.lyricsWindow.show()
      lyricsContext.isShow = true
    }
  })

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
